package com.joinlabs.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.joinlabs.entity.Order;
import com.joinlabs.entity.Orderitem;
import com.joinlabs.mapper.OrdersessionidMapper;
import com.joinlabs.service.IOrderService;
import com.joinlabs.service.IOrderSessionService;

@Controller
@RequestMapping("/pay")
@SessionAttributes(names = {"user","addr"})
public class PayAction {
	@Resource(name = "orderServiceImpl")
	private IOrderService oService;
	
	@Resource(name = "jsessionServiceImpl")
	private IOrderSessionService jsService;
	
	//用于存储网页的sessionId
	//static String  sessionId = null;
	
	@RequestMapping("/result")
	public ModelAndView payResult(ModelMap map,HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		
		//获取支付宝反馈信息
		Map<String,String> params = new HashMap<String,String>();
		//map保存
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			//System.out.println(valueStr);
			params.put(name, valueStr);
		}
		//订单号
		String orderId = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		String sessionId = jsService.getJSessionId(orderId);
		System.out.println("--------------");
		System.out.println("sessionId = "+ sessionId);
		//把sessionId添加到cookie中以重新获得session域的内容
		Cookie cookieOld = new Cookie("JSESSIONID", null);
		cookieOld.setMaxAge(0);
		response.addCookie(cookieOld);
		Cookie cookie = new Cookie("JSESSIONID", sessionId);
		cookie.setPath("/");
		response.addCookie(cookie);
		System.out.println(cookie.getValue());
		//System.out.println(request.getSession().getId());
		
		//System.out.println(cookie.getDomain());
		
		try {
			
			
			//验证 付款是否成功
			boolean signVerified = AlipaySignature.rsaCheckV1(params,
					"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoN4MIV8boej4IqHGQdlzaZcmMMLiCvfEAQhaSmfCFRmQr6vpbdjsrYB0n+g1HTNnR05VwTyu951qEPb7R+jbqo75vcdmERlVzSEOInGjE/Xvm4cMZgyHAweGwzdRIB6RhA8XeimW+gIcgEtoOy75gk//nK/e5/xhmI3n+Cb483Z2toS8gmX99AvTCmNV8cv6XkZFSx3A22vMpBlN8G0lZSrrd7yLhB+T/Jponu3z/LTM5cP1uG4PI5BMVYjFonTeMXCdujDnxQsCjqR1SN84WUmikJv8FcoyOQ/XxYu2nDbOdRd1FepN1dg89EWfVQL7vPIkWAbDTzFFHkc5qmTStQIDAQAB",
					"utf-8", "RSA2");
			
			//打印验证结果
			System.out.println("===================="+signVerified+"==================");
			
			if(signVerified) {
				
				//System.out.println("orderid = " + orderId);
				//修改订单信息
				int row = oService.payOver(orderId);
				
				if(row == 1){
					
					//支付完成后跳转回购物车界面
					return new ModelAndView("redirect:/shopcar/show");
				}
				
			
			}else {
				
				//将提示验签字符串转成iso-8859-1转发到网页上
				String r = "验签失败,请联系支付宝客服";
				byte[] b = r.getBytes("utf-8");
				String result = new String(b,"ISO-8859-1");
				response.getWriter().println(result);
			}
		
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //调用SDK验证签名

		
		return null;
	}

	
    
    //对订单进行支付
	@RequestMapping("/payorder")
	public void payOrder(HttpServletRequest request,HttpServletResponse response,Order order,long address) throws IOException {
		//System.out.println(order);
		order = oService.selectOrderByPK(order.getOrderId());
		
		order.setZyAid(address);
		
		oService.updata(order);
		//获取sessionId存储以应对跨域问题
		String sessionId = request.getSession().getId();
		System.out.println(sessionId);
		System.out.println(order.getOrderId());
		jsService.updataJsessionId(order.getOrderId(), sessionId);
		//System.out.println("sessionId = "+ sessionId);
		//获取alipay连接
		AlipayClient aliPayClient = new DefaultAlipayClient(
				"https://openapi.alipaydev.com/gateway.do",
				"2016100900646921",
				"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC0xW7sZicKOilk4ws3anHcXFZ9JtnM1yDkzDCAsxMlQH6nOC43uZav5E9DS8JxiaG64wZ57FoXbE8SqZ+l80/+QXZy68AbbIKEfPcerzVIFmFNszgyuADwEPcql9/qvYhfY0A0gUCE2PQp0fYQt1p96Oot3TDhG+ezSL8EgHoJfTpTyCWV6N3M6tGrrVd/CHHZRKkmpjXCQ0FEwxKASzGe7HkVNktD4wx+O58qRaATtNY/J1XjrXtY8ZWinHSq5+/PuN+azE1k0FU2uOJ6Xm8rH2x25amGsmxUYDGoTpNbFfilo7n0ovrtvAJIzBb40YKFbWY/V6qW2neIhRbZQjIPAgMBAAECggEAXcsi5p2KHBBZcfMr2rDsKv3uEjmaQGJOuugHMn+3q1hvXqwTru4odVLsnWotlWNn+uPYdGJhzE1yKajBIQXBt5aXssEHiDMg9UUxo0YdSy3xhrM6sXYvZmAnHn52vAFjRLrmkVeO9l7rMNez6LB5z2KOPwXJWsNz0N4p3lga+diSPPakgN84Wg+oug3uk/C7hNiLPlcjEwYSEGtpWqEClWIzE5Hts2svl0Gv4BYPP5ILhhTL8zDFgGW7aVOKvj0rgEXhq029T16+zq/+ctUkxikHJ434etrxGY2qaJ3eWvI9VnAaPnWC9tqmjaIs0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rgA8BD3Kpff6r2IX2NANIFAhNj0KdH2ELdafejqLd0w4Rvns0i/BIB6CX06U8gllejdzOrRq61Xfwhx2USpJqY1wkNBRMMSgEsxnux5FTZLQ+MMfjufKkWgE7TWPydV4617WPGVopx0qufvz7jfmsxNZNBVNrjiel5vKx9sduWphrJsVGAxqE6TWxX4paO59KL67bwCSMwW+NGChW1mP1eqltp3iIUW2UIyDwIDAQAB",
		        		"RSA2");
		
		
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		System.out.println("==========================创建支付宝连接");
		
		//同步的回调
		alipayRequest.setReturnUrl("http://127.0.0.1:8082/pay/result");
		
	
		//付款的基本参数封装(订单号,订单名称,付款金额,商品描述)
		//商户订单号
		String out_trade_no = order.getOrderId();
		//付款金额
		long sumPrice = 0;
		for (Orderitem item : (List<Orderitem>)order.getItems()) {
			sumPrice += item.getOrderPrice();
		}
		String total_amount = ""+sumPrice;
		//订单名称
		String subject = 
					((Orderitem) order.getItems().get(0)).getWaresName() + (order.getItems().size() > 1?"等多个商品":"");
		//商品描述
		String body = "";
		for (int i = 0; i < order.getItems().size(); i++) {
			body += ((Orderitem) order.getItems().get(0)).getWaresName()+"|";
		}
		
		//封装订单数据
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\","  
				+ "\"timeout_express\":\"10m\","	//超时时间
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
	
	
		try {
			//请求
			String result = aliPayClient.pageExecute(alipayRequest).getBody();
			System.out.println(result);
			//输出
			response.setContentType("text/html;charset=utf-8");
			
			
			response.getWriter().println(result);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
